#include "string_formatter.h"
#include "../base/debug.h"
#include "../base/error.h"
#include "resource_manager.h"

StringFormatter::StringFormatter(const CString& language) : language_(language)
{
	ASSERT1(!language.IsEmpty());
}

HRESULT StringFormatter::LoadString(int32 resource_id, CString* result)
{
	ASSERT1(result);

	HINSTANCE resource_handle = NULL;
	HRESULT hr = ResourceManager::Instance().GetResourceDll(language_, &resource_handle);
	if (FAILED(hr))
		return hr;

	const TCHAR* resource_string = NULL;
	int string_length = ::LoadString(resource_handle, resource_id, reinterpret_cast<TCHAR*>(&resource_string), 0);
	if (string_length <= 0)
		return HRESULTFromLastError();
	ASSERT1(resource_string && *resource_string);

	// resource_string is the string starting point but not null-terminated, so
	// explicitly copy from it for string_length characters.
	result->SetString(resource_string, string_length);

	return S_OK;
}

HRESULT StringFormatter::FormatMessage(CString* result, int32 format_id, ...)
{
	ASSERT1(result);
	ASSERT1(format_id != 0);

	CString format_string;
	HRESULT hr = LoadString(format_id, &format_string);
	if (FAILED(hr)) return hr;

	va_list arguments;
	va_start(arguments, format_id);
	result->AppendFormatV(format_string, arguments);
	va_end(arguments);

	return S_OK;
}